/**
 * Created by Administrator on 2017/3/13.
 */
 var flag = '';
 var _starttime = '';
$(function(){   
    flag = '';
    var NameMobile=JSON.parse(localStorage.getItem('NameMobile'));
    var orderHtml=sessionStorage.getItem('orderHtml');
    //加载购物车数据
    $.post(ajaxCar, function (res) {
        var data = JSON.parse(res);
        if (data.length == 0) {
            location.href=indexUrl;
        }
        var prices = 0, html = '',htmlDD = '',htmlSM='';
        for (var i = 0; i < data.length; i++) {
            _starttime = data[i].starttime;
            prices += Number(data[i].num) * Number(data[i].oprice);
            // if (data[i].deliverytype == 2) {
                htmlDD +='<div><img src=' + data[i].img + '><div>' +
                '<div class="lists_title">' + data[i].goodsname + '</div><div class="lists_detail"><span>￥' + data[i].price + '</span></div>'+
                '<div class="lists_num"><span><i></i></span></div></div></div></div>' +
                '<a class="weui-cell weui-cell_access" href="javascript:;">' +
                // '<div class="weui-cell__bd weui-cell_primary"><p>地点: '+data[i].store.storename+'</p></div></a>' +
                '<a class="weui-cell weui-cell_access" href="javascript:;">' +
                '<div class="weui-cell__bd weui-cell_primary"><p>时间: '+data[i].starttime+'</p></div></a>' +
                //'<a class="weui-cell weui-cell_access" href="javascript:;">' +
                    //'<div class="weui-cell__bd weui-cell_primary"><p>班级: '+data[i].starttime+'</p></div></a>' +
                // '<a class="weui-cell weui-cell_access" href="javascript:;">' +
                '<div class="weui-cell__bd weui-cell_primary">'
                //'<p>服务技师: '+data[i].jishi.nickname+'</p></div></a></div>';
            // }
        }
        htmlDD!=''&& htmlDD
        //    ='<a style="padding-left: 0" class="weui-cell weui-cell_access" href="javascript:;"><div class="weui-cell__bd weui-cell_primary">' +
        //'<p class="DDorSMtitle"><i class="iconal-gongsi"></i>到店消费</p></div></a><div>'+htmlDD+'</div>');
        htmlSM!=''&& htmlSM
        //    ='<a style="padding-left: 0;margin-top: 5px" style="margin-top: 5px;" class="weui-cell weui-cell_access noTop" href="javascript:;"><div class="weui-cell__bd weui-cell_primary">' +
        //'<p class="DDorSMtitle"><i class="iconal-locationfill"></i>上门服务</p></div></a><div>'+htmlSM+'</div>');
        html=htmlDD
            //+htmlSM;
        $('.footer span').html('￥' + prices.toFixed(2));
        $('.lists').html(html);
        $.get(addressmoren, function (res) {
            var data = JSON.parse(res);
            if (data.id) {
                var a = $("a[class*='address']");
                for (var i = 0; i < a.length; i++) {
                    $(a[i]).attr('data-addressid',data.id).children('div').html('<p>' + data.cname + '  ' + data.tel + '</p><p>' + data.province + data.city + data.county + '</p><p>' + data.detailed_address + '</p>');
                }
            }
        });
        //获取用户姓名电话
        if(NameMobile){
            $('input.name').val(NameMobile.name);
            $('input.englishName').val(NameMobile.enName);
            if(NameMobile.sex === '男'){
                $('#s11').attr('checked','checked')
            }else{
                $('#s12').attr('checked','checked')
            }
            $('input.mobile').val(NameMobile.mobile);
            // $('input.birth').val(NameMobile.birth);
            $('input.shenfengzheng').val(NameMobile.idcard);
            $('#select-class').val(NameMobile.garde);
            $('input .class_num').val(NameMobile.class_num);
        }
    });
    //获取用户姓名电话
    if(NameMobile){
        $('input.name').val(NameMobile.name);
        $('input.englishName').val(NameMobile.enName);
            if(NameMobile.sex === '男'){
                $('#s11').attr('checked','checked')
            }else{
                $('#s12').attr('checked','checked')
            }
            $('input.mobile').val(NameMobile.mobile);
            // $('input.birth').val(NameMobile.birth);
            $('input.shenfengzheng').val(NameMobile.idcard);
            $('#select-class').val(NameMobile.garde);
            $('input.class_num').val(NameMobile.class_num);
    }else{
        $.get(member_shaoniangong_view,function (res) {
            var data = JSON.parse(res);
            if(data.status == 1) {
                $('input.name').val(data.user.name);
                $('input.englishName').val(data.user.enName);
                if(data.user.sex === '男'){
                    $('#s11').attr('checked','checked')
                }else{
                    $('#s12').attr('checked','checked')
                }
                $('input.mobile').val(data.user.mobile);
                $('input.shenfengzheng').val(data.user.idcard);
                $('#select-class').val(data.user.garde);
                $('input.class_num').val(data.user.class_num);
            }
        })
    }
});


 // 出生年月
    // $("#time3").datetimePicker({
    //     times: function () {
    //         return [
    //             {
    //                 values:[''] 
    //             }
    //         ];
    //     },
    //     value: ' '   //后面有一个空格
    // }); 

// 年级选择
$('#select-class').select({
    title: "选择年级",
    items: [
        {
            title: '幼儿',
            value: '00'
        },
        {
            title: '幼儿小班',
            value: '01'
        },
        {
            title: '幼儿中班',
            value: '02'
        },
        {
            title: '幼儿大班',
            value: '03'
        },
        {
            title: '一年级',
            value: '04'
        },
        {
            title: '二年级',
            value: '05'
        },
        {
            title: '三年级',
            value: '06'
        },
        {
            title: '四年级',
            value: '07'
        },
        {
            title: '五年级',
            value: '08'
        },
        {
            title: '六年级',
            value: '09'
        },
        {
            title: '初一',
            value: '10'
        },
        {
            title: '初二',
            value: '11'
        },
        {
            title: '初三',
            value: '12'
        },
        {
            title: '高中',
            value: '13'
        },
        {
            title: '成人',
            value: '14'
        }
    ]
    });


//返回选择项目
$('.back').click(function(){
    location.href=indexUrl;
    //清空购物车
    $('.lists').html('');
});
//编辑按钮
$('.edit>a').click(function(){
    if($('.edit>a').html()=="编辑"){
        $('.edit>a').html('完成');
        $('.lists_num b').css('display','inline-block');
    }else{
        $('.edit>a').html('编辑');
        $('.lists_num b').css('display','none');
    }
});

///**编辑  数量加减**/
$('.lists_num .add').click(function(){
    $(this).prev('span').html($(this).prev('span').html()-0+1);
});
$('.lists_num .minus').click(function(){
    var minus=$(this).next('span');
    var self=this;
    if(parseInt(minus.html())==1){
        $.confirm("确定删除该商品?", function() {
            //点击确认后的回调函数
            $(self).parent().parent().parent().remove();
        }, function() {
            //点击取消后的回调函数
        });
    }else {
        minus.html(minus.html() - 0 - 1);
    }
});





//选择服务技师
function jishiCH(e){
    var choose=$(e).prev().prev().find('.weui-bar__item--on');
    if(choose.html()=='到店消费'&&$(e).prev().prev().find('.weui-tab__bd-item--active').find('p').html()=='请选择门店'){
        $.toast('请先选择门店','text');
        return false;
    }
    if($(e).prev().find('p').html()=='请选择服务时间'){
        $.toast('请先选择服务时间','text');
        setTimeout(function(){
            $(e).prev().click()
        },1000);
        return false;
    }
    if($('input.name').val()!=''||$('input.mobile').val()){
        var NameMobile={
            name:$('input.name').val(),
            mobile:$('input.mobile').val()
        };
        localStorage.setItem('NameMobile',JSON.stringify(NameMobile));
    }
    var dateTime=(new Date()).getFullYear()+'-'+$(e).prev().attr('data-day')+' '+$(e).prev().attr('data-startt');
    location.href=personnelUrl+'from=order&id='+$(e).parent().attr('data-id')+'&dateTime='+dateTime;
}
//立即支付按钮
function pay(self){
    console.log('wqwqwqwqwqw');
    if(_starttime == "1970-01-01 08:00") {
        $.toast('订单提交失败','cancel');
        return false;
    }
    if(!flag == '') {
        $.toast(flag, 'cancel');
    }
    flag = '请不要重复提交订单';
    var sex;
    if($('input.name').val()==''){
        $.toast('请输入姓名','cancel');
        return false;
    }
    if($('input.mobile').val()==''){
        $.toast('请收入手机号','cancel');
        return false;
    }
    if(!(/^1[34578]\d{9}$/.test($('input.mobile').val()))){
        $.toast('手机号填写有误','cancel');
        return false;
    }
    sex = $('.weui-cells_checkbox').find('.weui-check:checked').parent().next().text().trim();   //获取性别

    // if(!(/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/).test($('input.shenfengzheng').val())){
    //     $.toast('身份证号码填写有误','cancel')
    //     return false;
    // }
    var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"} 
    function isCardID(sId){ 
        var iSum=0 ;
        var info="" ;
        if(!/^\d{17}(\d|x)$/i.test(sId)){
            $.toast("你输入的身份证长度或格式错误",'cancel') 
            return false
        }; 
        sId=sId.replace(/x$/i,"a"); 
        if(aCity[parseInt(sId.substr(0,2))]==null) {
            $.toast("你的身份证地区非法",'cancel') 
            return false
        }; 
        sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2)); 
        var d=new Date(sBirthday.replace(/-/g,"/")) ;
        if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate())){
            $.toast("身份证上的出生日期非法",'cancel') 
            return false
        }; 
        for(var i = 17;i>=0;i --) iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11) ;
        if(iSum%11!=1) {
            $.toast("你输入的身份证号非法",'cancel') 
            return false
        }; 
        //aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女") ;//此次还可以判断出输入的身份证号的人性别
        return true;
    }
    console.log(isCardID($('input.shenfengzheng').val()));
    if(isCardID($('input.shenfengzheng').val())){
        //return true;
    }else{
        return false;
    }
     // var birth = $('#time3').val().trim();
    // var enName = $('input.englishName').val().replace(/[\u4e00-\u9fa5]|(·)/g,"");
    
    $.get(
        checkOrder,
        {
            nickN: $('input.name').val(),
            // birth: birth, 
            sex: sex,
            idcard: $('input.shenfengzheng').val(),
            phone: $('input.mobile').val(),
            remark: $('input.remark').val(),
            class_num: $('input .class_num').val()  
        },
        function (res) {
            var data = JSON.parse(res);
            if(JSON.parse(res).bstatus=='0'){
                $.toast('预约失败，该活动不能重复参加', 'cancel');
                setTimeout(function(){
                    location.reload();
                },1500);
                return false;
            }
            if(data.boom == 1) {
                $.toast('名额已满,预约失败'); 
                setTimeout(function() {
                    window.location.href = indexUrl;
                }, 1500);
                return;
            }
            localStorage.setItem('NameMobile', JSON.stringify({
                name: $('input.name').val(),
                mobile: $('input.mobile').val(),
                // birth: birth,
                sex: sex,
                idcard: $('input.shenfengzheng').val(),
                class_num: $('input .class_num').val()
            }));
            
            console.log(data.orderno); 
            if (!data.orderno) {
                $.toast('预约失败，请重新下单', 'cancel');
                setTimeout(function(){
                    location.reload();
                },1500);
                return false;
            }
             
            if(data.pay_price === 0){
                // $.get(checkOrder, {orderno: data.orderno}, function (res) {   //免费通道
                //     var response = JSON.parse(res);
                //     if(response.boom == 1) {
                //         $.toast('库存不足','cancel');
                //         return;
                //     }
                //     console.log(response);
                    // if (response.status == 0) { 
                        console.log(data.pay_price);
                        $.get(check_payresult,{ 
                            orderno: data.orderno,
                            transid: '订单免费',
                            fee: data.pay_price
                        },function (res) {
                            console.log(res);
                            res = JSON.parse(res);
                            // if(uniacid == '4'){                 //测试站
                            //    if(res.status == 0){          
                            //         location.href=paySucc+'&orderno='+data.orderno;    
                            //     }else{
                            //         $.toast("订单提交失败",'cancel');
                            //         location.href=paySucc+'&orderno='+data.orderno+'&errno=1';          
                            //     } 
                            // }else{
                                location.href=paySucc+'&orderno='+data.orderno;    
                            // } 
                        })
                        return false;
                    // }
                // })      
            }else{
                var orderno = data.orderno;
            // $.get(checkOrder, {orderno: data.orderno}, function (res) {
            //     var data = JSON.parse(res);
            //     if(data.boom == 1) {
            //             $.toast('库存不足');
            //             return;
            //         }
            //     if (data.status == 0) {
                    var paytype = 'wechat';

                    $.post(paycash, {orderno: orderno, paytype: paytype}, function (m) {  
                        if (!m.errno) {
                            m.data.timeStamp = String(m.data.timeStamp);
                            WeixinJSBridge.invoke('getBrandWCPayRequest', {
                                'appId': m.data.appid ? m.data.appid : m.data.appId,
                                'timeStamp': m.data.timeStamp,
                                'nonceStr': m.data.nonceStr,
                                'package': m.data.package,
                                'signType': m.data.signType,
                                'paySign': m.data.paySign
                            }, function (res) {
                                $('.footer a').attr('data-orderno', orderno);
                                if (res.err_msg == 'get_brand_wcpay_request:ok') {
                                    location.href = paycash + "&orderno=" + orderno + "&paytype=" + paytype + "&done=1";
                                } else {
                                    $.toast("已取消支付", 'cancel');
                                    setTimeout(function () {
                                        location.href = orderUrl
                                    }, 1000);
                                }
                            });
                        }
                    }, "json");
            //     } else if (data.status == 1) {
            //         $.toast('该项目预约时间已满，请重新下单', 'cancel');
            //         location.href = indexUrl;
            //         return false;
            //     }
            // })
        }
    })
    $(self).removeAttr('onclick').css({
        'background': '#ccc'
    });
}



///**监听用户返回按钮**/
// var _system={
//     $:function(id){return document.getElementById(id);},
//     _client:function(){
//         return {w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight,bw:document.documentElement.clientWidth,bh:document.documentElement.clientHeight};
//     },
//     _scroll:function(){
//         return {x:document.documentElement.scrollLeft?document.documentElement.scrollLeft:document.body.scrollLeft,y:document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop};
//     },
//     _cover:function(show){
//         if(show){
//             this.$("cover").style.display="block";
//             this.$("cover").style.width=(this._client().bw>this._client().w?this._client().bw:this._client().w)+"px";
//             this.$("cover").style.height=(this._client().bh>this._client().h?this._client().bh:this._client().h)+"px";
//         }else{
//             this.$("cover").style.display="none";
//         }
//     },
//     _guide:function(click){
//         this._cover(true);
//         this.$("guide").style.display="block";
//         this.$("guide").style.top=(_system._scroll().y+5)+"px";
//         window.onresize=function(){_system._cover(true);_system.$("guide").style.top=(_system._scroll().y+5)+"px";};
//         if(click){_system.$("cover").onclick=function(){
//             _system._cover();
//             _system.$("guide").style.display="none";
//             _system.$("cover").onclick=null;
//             window.onresize=null;
//         };}
//     }
// }
// pushHistory();
// setTimeout(function () {
//     window.addEventListener("popstate", function(e) {
//         showBox("再按一次退出程序", 1000, function() {
//             pushHistory();
//         });
//     }, true);
// }, 1000);

// function pushHistory() {
//     var state = { title: "title", url: "#" };
//     window.history.pushState(state, "title", "#");
// }

// function showBox(msg, timeOut, onTimeOut) {
//     if (typeof timeOut === "undefined") timeOut = 2000;
//     setTimeout(function() {

//         if (typeof onTimeOut !== "undefined") {  onTimeOut();
//             tipsBox.createPayBox();
//         }
//     }, timeOut);
// }

// var tipsBox = {}
// tipsBox.container = '#tips-box';
// tipsBox.createPayBox = function() {
//     location.href=indexUrl;
// }
// tipsBox.hideTipsBox = function() { //关闭提提示框
//     $(tipsBox.container).hide();
// }
// tipsBox.tipsBoxCenter = function(_this) { //提示框居中
//     var windowHeight = $(window).height();
//     var _thisHeight = $(_this).css('height').replace('px','');
//     var top = parseFloat(windowHeight - _thisHeight) / 2;
//     $(_this).css('marginTop',top);
// }





















